package ChatDemo.server.Handler;

import ChatDemo.message.GroupCreateRequestMessage;
import ChatDemo.message.GroupCreateResponseMessage;
import ChatDemo.server.session.Group;
import ChatDemo.server.session.GroupSession;
import ChatDemo.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;


@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();

        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        if (group==null){
            ctx.writeAndFlush(new GroupCreateResponseMessage(true,"成功！"));
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel:membersChannel)
                channel.writeAndFlush(new GroupCreateResponseMessage(true,"您已被拉入"+groupName));
        }else {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false,"存在！"));
        }
    }
}
